package weixin.channel.gateway;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import weixin.channel.service.MessageGateway;

/**
 * <article>
 * <header>微信Gateway 为微信专用通信</header>
 * <p>
 * 我是正文</p>
 * </article>
 *
 * @author 张森
 */
@Path("/")
@Component("weixinChannel")
public class WeixinChannel {
    
    @Autowired
    MessageGateway messageGateway;
    
    Logger logger = LoggerFactory.getLogger(WeixinChannel.class);

    @Path("/")
    @Consumes(MediaType.TEXT_PLAIN)
    @Produces(MediaType.TEXT_PLAIN)
    @GET
    public String message(
            @QueryParam("signature") String signature,
            @QueryParam("timestamp") String timestamp,
            @QueryParam("nonce") String nonce,
            @QueryParam("echostr") String echostr
    ) {
        String msgSignature = null;
        String encryptType = null;
        String context = null;
        logger.info("signature={}, timestamp={}, nonce={}, echostr={}", signature, timestamp, nonce, echostr);
        return null;
    }

    @Path("/")
    @Consumes({MediaType.TEXT_XML, MediaType.APPLICATION_FORM_URLENCODED})
    @Produces(MediaType.TEXT_PLAIN)
    @POST
    public String message(
            @QueryParam("signature") String signature,
            @QueryParam("timestamp") String timestamp,
            @QueryParam("nonce") String nonce,
            @QueryParam("echostr") String echostr,
            @QueryParam("encrypt_type") String encryptType,
            @QueryParam("msg_signature") String msgSignature,
            String context
    ) throws IOException {
        logger.info("signature={}, msg_signature={}, timestamp={}, nonce={}, echostr={}, encrypt_type={} ,message={}", signature, msgSignature, timestamp, nonce, echostr, encryptType, context);
        
        return null;
    }

    private String body(InputStream in) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String message = sb.toString();
        return message;
    }
}
